package com.epam.player.desktop.logic;

import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.HashMap;
import java.util.Map;

import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPasswordField;
import javax.swing.JTextField;

import com.epam.player.desktop.common.Constant;
import com.epam.player.desktop.view.MainForm;
import com.epam.player.vkapi.authentication.Authentication;
import com.epam.player.vkapi.exceptions.CredentialsWrongException;
import com.epam.player.vkapi.exceptions.TemporarilyUnavailableServiceException;

public class ActionClickEventLogin implements ActionListener {

	private JTextField textField;
	private JPasswordField passwordField;
	private JLabel lblMessage;
	private JFrame loginForm;
	private JButton button;

	public ActionClickEventLogin(JButton button, JLabel lblMessage,
			JFrame loginForm, JTextField textField, JPasswordField passwordField) {
		this.textField = textField;
		this.passwordField = passwordField;
		this.lblMessage = lblMessage;
		this.loginForm = loginForm;
		this.button = button;
	}

	@Override
	public void actionPerformed(ActionEvent e) {
		Authentication authentication = new Authentication();
		PropertiesLoader propertiesLoader = new PropertiesLoader();
		Map<String, String> data = new HashMap<String, String>();
		String email = textField.getText();
		String pass = new String(passwordField.getPassword());
		data.put(Constant.EMAIL, email);
		data.put(Constant.PASS, pass);
		try {
			authentication.loginToVK(email, pass);
			button.setEnabled(false);
			propertiesLoader.saveProperties(data);
			lblMessage.setText("");
			loginForm.setVisible(false);
			new MainForm().start();
		} catch (CredentialsWrongException e1) {
			button.setEnabled(true);
			lblMessage.setText("Wrong credentials!");
		} catch (TemporarilyUnavailableServiceException e1) {
			button.setEnabled(true);
			lblMessage.setText("Wrong TemporarilyUnavailableServiceException");
		}

	}

}
